const Raven = require('./raven.js');
Raven.config('http://c11d5edbb9404be995ca6c5ae0b0c2c7@sentry.oneqing.com/97', {
    release: '20180810'
}).install()

wx.doodoo = {};
wx.doodoo.version = "1.0";
wx.doodoo.host = "127.0.0.1:3001";
wx.doodoo.secure = true; // 开发模式
wx.doodoo.openLoginStatus = true;
wx.doodoo.noAuthorizationRequestOptions = [];
wx.doodoo.getProtocol = (socket = false) => {
    if (socket) {
        return wx.doodoo.secure ? "wss://" : "ws://";
    } else {
        return wx.doodoo.secure ? "http://" : "https://";
    }
}
wx.doodoo.getRequestOptions = function (options) {
    let url = options.url;
    let header = options.header || {};
    let protocol = wx.doodoo.getProtocol();

    if (options.url.indexOf("https://") !== 0 && options.url.indexOf("http://") !== 0) {
        url = `${protocol}${wx.doodoo.host}${options.url}`;
    } else {
        if (options.url.indexOf(`${protocol}${wx.doodoo.host}`) !== 0 && !options.noProxy) {
            url = `${protocol}${wx.doodoo.host}`;
            header.Proxy = options.url;
        }
    }
    header = Object.assign(header, {
        Token: wx.getStorageSync("token"),
        "Content-Type": "application/json"
    });
    return Object.assign(options, {
        url,
        header
    });
};
wx.doodoo.connectSocket = function (options) {
    let protocol = wx.doodoo.getProtocol(true);

    if (options.url.indexOf(`${protocol}${wx.doodoo.host}`) !== 0) {
        options = Object.assign(options, {
            url: `${protocol}${wx.doodoo.host}?Proxy=${encodeURIComponent(
                options.url
            )}`
        });
    }

    return wx.connectSocket(options);
};
wx.doodoo.request = function (options) {
    return wx.request(wx.doodoo.getRequestOptions(options));
};
wx.doodoo.login = function (cb) {
    wx.getUserInfo({
        success: res => {
            wx.login({
                success: resl => {
                    const code = resl.code;
                    const data = {
                        code: code,
                        encryptedData: res.encryptedData,
                        iv: res.iv
                    };
                    wx.doodoo.request({
                        url: "/app/api/public/wxaLogin",
                        method: "POST",
                        noProxy: true,
                        data: data,
                        success: res => {
                            if (res && res.data.errmsg == 'ok') {
                                wx.setStorageSync("token", res.data.data.token);
                                typeof cb == "function" && cb(res);
                            } else {
                                wx.showModal({
                                    content: res.data.errcode,
                                    showCancel: false
                                });
                                return res;
                            }
                        },
                        fail: res => {
                            console.error("wx.doodoo.login request Fail" + res.errMsg);
                        }
                    });
                }
            });
        },
        fail: res => {
            console.error("wx.doodoo.login wx.getUserInfo Fail" + res.errMsg);
            if (wx.doodoo.openLoginStatus) {
                wx.doodoo.openLoginStatus = false;
                console.log("start login");
                // 授权登录页面
                wx.navigateTo({
                    url: "/pages/login/index",
                    fail: res => {
                        console.log(res);
                    }
                });
            }
            setTimeout(() => {
                wx.doodoo.openLoginStatus = true;
            }, 1000);
        }
    });
};
wx.doodoo.fetch = function (url, options = {}) {
    options.url = url;
    return new Promise((resolve, reject) => {
        options.success = res => {
            if (res.statusCode == 401) {
                wx.showModal({
                    content: res.data.errcode,
                    showCancel: false
                });
                wx.doodoo.noAuthorizationRequestOptions.push(options);
                wx.doodoo.login(() => {
                    let length = wx.doodoo.noAuthorizationRequestOptions.length;
                    for (let i = 0; i < length; i++) {
                        wx.doodoo.request(wx.doodoo.noAuthorizationRequestOptions.pop());
                    }
                });
            } else {
                resolve(res);
            }
        };
        options.fail = res => {
            reject(res);
        };
        wx.doodoo.request(options);
    });
};
wx.doodoo.upload = function (options) {
    return wx.uploadFile(wx.doodoo.getRequestOptions(options));
};

App({
    onError: function (error) {
        console.log('onError')
        Raven.captureException(error, {
            level: 'error'
        })
    }
});